<template>
  <div class="baidu-map q-pa-xs">
    <baidu-map
      class="bm-view"
      ak="3V3i3Kf3IZjUr111wjQ8vvyRiu1GY1jd"
      :center="center"
      :zoom="zoom"
      @ready="handler"
      :scroll-wheel-zoom="true"
      :double-click-zoom="true"
    >
      <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
      <!-- #TODO @pablo 这里的三元运算符还有一点点改进空间
        :icon = "{
          size: {width: 50, height: 35},
          url: `../assets/${Number(user.status)===1 ? 'normal' : Number(user.status)===2 ?  'alarm' : 'pre'}_marker.png`
        }"
       -->
      <bm-marker
        v-for="user in userOnline"
        :key="user.userID"
        :position="{lat: user.gpsLatitude, lng:user.gpsLongtitude}"
        :dragging="false"
        :icon="Number(user.status)===1?{
            url: '../assets/normal_marker.png',
            size: { width: 50, height: 35 }
          }:((Number(user.status))===2?{
            url: '../assets/alarm_marker.png',
            size: { width: 50, height: 35 }
          }:{
            url: '../assets/pre_marker.png',
            size: { width: 50, height: 35 }
          })"
        @mouseover="showInfoWindow(user)"
      >
        <bm-info-window
          :position="{lat: user.gpsLatitude, lng: user.gpsLongtitude}"
          :show="user.show"
          @close="closeInfoWindow(user)"
          class="info-Window column"
        >
          <div>
            姓名：
            <strong v-html="user.userName"></strong>
          </div>
          <q-item v-if="Number(user.status)===1" class="bg-positive">一切正常</q-item>
          <template v-if="Number(user.status)===2">
            <!-- #TODO @pablo 有三个问题：
              1、一般情况下，处理和拒绝的逻辑是不一样的，通常需要使用不同的函数去处理
              2、 一般尽量不在简单函数里面使用Boolean值去做flag，虽然少写一个函数，但是在函数内部，多嵌套了一层逻辑，业务耦合会很严重，代价太高；
              3、 即使最后不得不加flag，也是把flag作为函数入参的最后一个；
            -->
            <q-btn class="bg-positive" @click.native.stop="dealOrRefuse(true,user.userID)">处理</q-btn>
            <q-btn class="bg-negative" @click.native.stop="dealOrRefuse(false,user.userID)">拒绝</q-btn>
          </template>
          <template v-if="Number(user.status)===3">
            <q-item class="bg-positive">处理中</q-item>
            <q-btn class="bg-negative" @click.native.stop="endGuide(user.userID)">处理完成</q-btn>
          </template>
        </bm-info-window>
      </bm-marker>
    </baidu-map>
  </div>
</template>

<script>
import BaiduMap from 'vue-baidu-map/components/map/Map.vue'
import BmNavigation from 'vue-baidu-map/components/controls/Navigation.vue'
import BmMarker from 'vue-baidu-map/components/overlays/Marker.vue'
import BmInfoWindow from 'vue-baidu-map/components/overlays/InfoWindow.vue'
import httpPost from '../httpPost.js'
export default {
  name: 'PageMap',
  components: {
    BaiduMap,
    BmNavigation,
    BmMarker,
    BmInfoWindow
  },
  data () {
    return {
      center: { lng: 0, lat: 0 },
      zoom: 3,
      markerPoint: { lng: 113.27, lat: 23.13 },
      show: false,
      jsnData: {
        commonKey: 200,
        appKey: 1,
        userID: this.$q.cookies.get('userID'),
        data: {}
      },
      jsnDataDealRequest: {
        commonKey: 403,
        appKey: 5,
        userID: '',
        data: { userID: '' }
      },
      jsnDataEndGuide: {
        commonKey: 403,
        appKey: 6,
        userID: '',
        data: { responseID: '', userID: '' }
      },
      userOnline: null,
      userNormal: null,
      userInGuide: null,
      userInRequest: null,
      timerFreshMapData: '',
      showUser: null
    }
  },
  methods: {
    /* #TODO: @pablo 变量 函数名命名时，不要用这种抽象的名字，而且在大部分编程语言中，handler这样的很大概率是保留字。建议命名时，把函数行为或者作用体现在函数名中 */
    handler ({ Bmap, map }) {
      this.center.lng = 113.27
      this.center.lat = 23.13
      this.zoom = 11
    },
    showInfoWindow (user) {
      const me = this
      /** set current user in userNormal data */
      this.userOnline = this.userOnline.map(item => {
        /** set the last show false which is true first,then set the new user's show true */
        if (item.show) {
          item.show = false
          this.showUser = null
        }
        if (item.userID === user.userID) {
          item.show = true
          /**  recorder the infowindow need to be shown for the next time use after freshdata */
          me.showUser = user
        }
        return item
      })
    },
    closeInfoWindow (user) {
      const me = this
      this.userOnline = this.userOnline.map(item => {
        if (item.show) {
          item.show = false
          me.showUser = null
        }
        return item
      })
      /** reset the the showUserId */
    },
    async freshData () {
      this.jsnData.userID = this.$q.cookies.get('userID')
      const { data: { data } } = await httpPost(this.jsnData)
      this.userOnline = data
      /** mock gps data */
      // this.userOnline = data.map(item => ({
      //   ...item,
      //   gpsLatitude: Math.random() * 100,
      //   gpsLongtitude: Math.random() * 100,
      //   show: false
      // }))
      // console.log('this.userOnline[1].status', this.userOnline[1].status)
      // this.userOnline[1].status = '2'
      // this.userOnline[0].status = '3'
      // eslint-disable-next-line
      // [this.userOnline[1].status, this.userOnline[0].status] = ['2', '3']
      /* 获取请求指导信息未被处理人员信息，同上 */
      this.userInRequest = this.userOnline.filter(item => item.status === '2')
      this.userInGuide = this.userOnline.filter(item => item.status === '3')
      /** confirm whether need to show InfoWindow */
      if (this.showUser !== null) this.showInfoWindow(this.showUser)
      /* 向远程指导事件模块传递数据 */
      this.$emit('transformUserInGuide', this.userInGuide)
      this.$emit('transformUserInRequest', this.userInRequest)
      /** the next time freshData */
      setTimeout(this.freshData, 2000)
    },
    dealOrRefuse (status, userID) {
      return status ? this.dealRequest(userID) : this.endGuide(userID)
    },
    async dealRequest (userID) {
      this.jsnDataDealRequest.userID = this.$q.cookies.get('userID')
      this.jsnDataDealRequest.data.userID = userID
      const res = await httpPost(this.jsnDataDealRequest)
      console.log('res------', res)
    },
    /** refuse and endGuide is the same api */
    async endGuide (userID) {
      this.jsnDataEndGuide.userID = this.$q.cookies.get('userID')
      /** need to be comfirmed */
      this.jsnDataEndGuide.data.responseID = this.$q.cookies.get('userID')
      this.jsnDataEndGuide.data.userID = userID
      await httpPost(this.jsnDataEndGuide)
    }
  },
  async created () {
    // 刷新数据
    this.freshData() // 先立即执行；
  },
  /* #TODO: @pablo 这个created()和freshData()执行的操作是一样的吧？这种情况下，应该把共同执行的部分抽出一个函数，就是你这里的refreshdata(),如果要保证refreshdata立即执行之后再进入异步队列，参考用法： */
  beforeDestroy () {
    clearInterval(this.timerFreshMapData)
    this.timer = null
  }
}
</script>

<style lang="stylus">
.baidu-map {
  .bm-view {
    width: 100%;
    height: 100%;
  }

  width: 100%;
  height: 100%;
}
</style>
